package com.hzit.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzit.entity.User;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.web.servlet.oauth2.resourceserver.OAuth2ResourceServerSecurityMarker;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class MyUserDetailService implements UserDetailsService {
	@Autowired
	private IUserService userService;
	//1. 在此方法中实现用户认证功能
	//username: 代表用户在表单中输入的用户名
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//1.1 根据用户名查询用户
		User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
		//1.2 如果查不到user对象，就抛出异常
		if(user == null){
			throw new UsernameNotFoundException("用户名不存在！");
		}
		//1.3 得到用户密码
		String password = user.getPassword();

		//1.4 定义用户的权限或角色列表
		Collection<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,query,ROLE_sale");

		//1.5 返回这个user对象
		return new org.springframework.security.core.userdetails.User(username,password,authorities);
	}

	public static void main(String[] args) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String encode = encoder.encode("123");
		System.out.println("encode = " + encode);

	}
}
